package com.test.boot.http.rpc.server.config;

import com.test.boot.http.rpc.api.service.DemoService;
import org.springframework.boot.context.embedded.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.remoting.httpinvoker.HttpInvokerServiceExporter;
import org.springframework.web.context.support.HttpRequestHandlerServlet;

import java.util.Date;

/**
 * Created by hujianjun on 1/7 0007.
 */
@Configuration
public class DemoServiceServletConfig {

    @Bean
    public ServletRegistrationBean demoServletRegistrationBean() {
        HttpRequestHandlerServlet servlet = new HttpRequestHandlerServlet();
        ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean();
        servletRegistrationBean.setServlet(servlet);
        servletRegistrationBean.setName("demoServiceExporter");        //映射为bean的名字
        servletRegistrationBean.addUrlMappings("/demo");
        servletRegistrationBean.setEnabled(true);
        return servletRegistrationBean;
    }

    @Bean
    public DemoService demoService() {
        DemoService service = new DemoService() {
            StringBuilder sb = new StringBuilder();
            @Override
            public String testDemo(String s) {
                sb.append(new Date()+":"+s);
                return sb.toString();
            }
        };
        return service;
    }

    @Bean(name="demoServiceExporter")
    public HttpInvokerServiceExporter httpInvokerServiceExporter() {
        HttpInvokerServiceExporter exporter = new HttpInvokerServiceExporter();
        exporter.setServiceInterface(DemoService.class);
        exporter.setService(demoService());      // 设置对应的实例，该实例会作为参数注入进来
        return exporter;
    }
}
